package com.arron.algorithm.leetcodetop100.双指针;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class 反转字符串中的单词 {


    /**
     *  双指针
     * @param s
     * @return
     */
    public String reverseWords(String s) {
        s= s.trim();
        char[] array = s.toCharArray();

        List<String> res = new ArrayList<>();


        for (int i = array.length-1; i >=0 ;) {
             int j = i;
            while (j>=0 && array[j]!=' '){
                j--;
            }
             res.add( s.substring(j+1,i+1));
            while (j>=0 && array[j] == ' '){
                j--;
            }
            i=j;
        }
        return String.join(" ", res);
    }


    /**
     *  使用api 先反转整个字符串，再对每个单词进行反转
     * @param s
     * @return
     */
    public String reverseWords01(String s) {

        StringBuffer stringBuffer = new StringBuffer(s);
        StringBuffer reverse = stringBuffer.reverse();
        String s1 = reverse.toString();
        String[] s2Arrays = s1.split(" ");
        List<String> res = new ArrayList<>();
        for (String s2 : s2Arrays) {
            if (s2.trim().length() ==0){
                continue;
            }
         res.add(new StringBuffer(s2).reverse().toString());
        }
        String collect = String.join(" ", res);

        return collect.trim();
    }

    public static void main(String[] args) {
        String s = "the sky is blue";

        反转字符串中的单词 fz = new 反转字符串中的单词();
        System.out.println(fz.reverseWords(s));
    }

}
